package com.fpx.order.plat.bussiness.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fpx.api.bean.Exception.CheckDataException;
import com.fpx.order.plat.bussiness.dao.log.IPullOrderLogDao;
import com.fpx.order.plat.bussiness.entity.CustomerShop;
import com.fpx.order.plat.bussiness.entity.PullOrderLog;
import com.fpx.order.plat.bussiness.entity.PullorderLogFail;
import com.fpx.order.plat.bussiness.entity.ResponseMessage;
import com.fpx.order.plat.bussiness.plat.base.IPlatOrderHandler;
import com.fpx.order.plat.bussiness.service.customer.ICustomerShopService;
import com.fpx.order.plat.bussiness.system.PlatConstants;
import com.fpx.order.plat.bussiness.vo.OrderDealResult;
import com.fpx.order.plat.common.utils.DateFormatUtils;

/**
 * 
 * desc: ManuallyGetPaltOrderController 
 * 	手动拉单Controller层
 * @author xiangtao(xiangtao@4px.com)
 * @date 2015年12月21日 下午6:17:09
 * @version 1.0
 */

@Controller
@RequestMapping("/manually")
public class ManuallyGetPaltOrderController {
	
	
	private final static Logger LOGGER = Logger.getLogger(ManuallyGetPaltOrderController.class);
	
	@Autowired
	@Qualifier("ebayPlatOrderHandler")
	private IPlatOrderHandler ebayPlatOrderHandler;
	
	@Autowired
	@Qualifier("amazonPlatOrderHandler")
	private IPlatOrderHandler amazonPlatOrderHandler;
	
	@Autowired
	@Qualifier("smtPlatOrderHandler")
	private IPlatOrderHandler smtPlatOrderHandler;
	
	@Autowired
	private ICustomerShopService customerShopService;
	
	@Autowired
	private IPullOrderLogDao pullOrderLogDao;
	
	protected SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
	
	/**
	 * 
	 * <p>Title: manuallyGetOrder</p>
	 * <p>Desc: 手动拉单接口</p>
	 * @author xiangtao(xiangtao@4px.com)
	 * @date 2015年12月23日 下午2:41:56 
	 * @version 1.0
	 * @param request
	 * @param map
	 * @return ResponseMessage
	 */
	@ResponseBody
	@RequestMapping(value="/getPaltOrder",method = RequestMethod.POST)
	public String manuallyGetOrder(HttpServletRequest request){
		LOGGER.info("手动拉单开始.....");
		ResponseMessage responseMessage=new ResponseMessage();
		
		List<OrderDealResult>  orderDealResults=null; 
		//手工拉单只记录失败日志
	    PullOrderLog pullOrderLog=new PullOrderLog();
	    Date beginTime = new Date(); 
		pullOrderLog.setPull_date_begin(dateFormat.format(beginTime));//拉单开始时间
		try{
			//检校请求参数
			checkRequestParam(request);
			CustomerShop customerShop=new CustomerShop();
			
			String cs_id=request.getParameter("cs_id");
			customerShop.setCs_id(cs_id);
			List<CustomerShop> customerShopLst=
						customerShopService.findByObjCustomer(customerShop);
			if(customerShopLst==null||customerShopLst.size()==0){
				throw new CheckDataException("店铺:【"+cs_id+"】不存在!");
			}
			customerShop=customerShopLst.get(0);
			pullOrderLog.setFk_cm_id(customerShop.getCm_id());//客户id
			pullOrderLog.setFk_cs_code(customerShop.getCs_id());//商铺ID
			String startTime = request.getParameter("start_time");
			String  endTime = request.getParameter("end_time");
			String platCode= request.getParameter("platform_code")!=null?request.getParameter("platform_code"):"";
			if(PlatConstants.ORDER_SOURCE_EBAY.equals(platCode)){
				pullOrderLog.setCs_platform_code(PlatConstants.ORDER_SOURCE_EBAY);//平台号
				orderDealResults= ebayPlatOrderHandler.getOrderByCustomer(customerShop, startTime, endTime, 1);
			}else if(PlatConstants.ORDER_SOURCE_AM.equals(platCode)){
				pullOrderLog.setCs_platform_code(PlatConstants.ORDER_SOURCE_AM);//平台号
				orderDealResults= amazonPlatOrderHandler.getOrderByCustomer(customerShop, startTime, endTime, 1); 
			}else if(PlatConstants.ORDER_SOURCE_SMT.equals(platCode)){
				pullOrderLog.setCs_platform_code(PlatConstants.ORDER_SOURCE_SMT);//平台号
				orderDealResults= smtPlatOrderHandler.getOrderByCustomer(customerShop, startTime, endTime, 1); 
			}else{
				throw new CheckDataException("暂时不支持【"+platCode+"】平台!");
			}
		}catch(CheckDataException e){
			LOGGER.error("手动拉单结束---请求参数异常:"+e.getMessage());
			return "false";
		}catch(Exception e){
		   	 Date endTime = new Date(); 
		   	 pullOrderLog.setPull_sign(PlatConstants.IS_PULL_SIGN_N);
		     pullOrderLog.setPull_date_end(dateFormat.format(endTime));//拉单结束时间
		     if(StringUtils.isNotEmpty(pullOrderLog.getFk_cm_id())&&
		    			 StringUtils.isNotEmpty(pullOrderLog.getFk_cs_code())){
		    	 try{ 
				    pullOrderLogDao.savePullOrderLog(pullOrderLog);
				    PullorderLogFail LogFail=new PullorderLogFail();
					LogFail.setError_msg(e.getMessage());
					LogFail.setFk_pol_id(pullOrderLog.getPol_id());
					pullOrderLogDao.savePullLogFail(LogFail);
		    	 }catch(Exception ex){
			    	LOGGER.error("---商家:["+pullOrderLog.getFk_cm_id()+"]-商铺ID:["+pullOrderLog.getFk_cs_code()+"]-"
			    			+ "【保存"+pullOrderLog.getCs_platform_code()+" 平台 手动拉单失败日志时异常】  "+e.getMessage());
			    	
		    	 }
		     }
		     LOGGER.error("手动拉单结束---发生异常:"+e.getMessage());
			
			 return "false";
		}
		int a=0;
		for (OrderDealResult orderDealResult : orderDealResults) {
			if("0".equals(orderDealResult.getRsCode())){
					a++;
			}
		}
		responseMessage.setRsCode(PlatConstants.IS_PULL_SIGN_Y);
		responseMessage.setOrderSuccessNum(a+"");
		responseMessage.setRsDesc("拉单成功");
		LOGGER.info("手动拉单结束---拉单成功");
		return "true";
	}
	
	
	@ResponseBody
	@RequestMapping(value="/getPaltOrderJsp",method = RequestMethod.POST)
	public ResponseMessage manuallyGetOrder(@RequestBody Map<String,String> resMap){
		LOGGER.info("手动拉单开始.....");
		ResponseMessage responseMessage=new ResponseMessage();
		
		List<OrderDealResult>  orderDealResults=null; 
		//手工拉单只记录失败日志
	    PullOrderLog pullOrderLog=new PullOrderLog();
	    Date beginTime = new Date(); 
		pullOrderLog.setPull_date_begin(dateFormat.format(beginTime));//拉单开始时间
		try{
			//检校请求参数
			checkRequestParam(resMap);
			CustomerShop customerShop=new CustomerShop();
			
			String cs_id=resMap.get("cs_id");
			customerShop.setCs_id(cs_id);
			List<CustomerShop> customerShopLst=
						customerShopService.findByObjCustomer(customerShop);
			if(customerShopLst==null||customerShopLst.size()==0){
				throw new CheckDataException("店铺:【"+cs_id+"】不存在!");
			}
			customerShop=customerShopLst.get(0);
			pullOrderLog.setFk_cm_id(customerShop.getCm_id());//客户id
			pullOrderLog.setFk_cs_code(customerShop.getCs_id());//商铺ID
			String startTime = resMap.get("start_time");
			String  endTime = resMap.get("end_time");
			String platCode= resMap.get("platform_code")!=null?resMap.get("platform_code"):"";
			if(PlatConstants.ORDER_SOURCE_EBAY.equals(platCode)){
				pullOrderLog.setCs_platform_code(PlatConstants.ORDER_SOURCE_EBAY);//平台号
				orderDealResults= ebayPlatOrderHandler.getOrderByCustomer(customerShop, startTime, endTime, 1);
			}else if(PlatConstants.ORDER_SOURCE_AM.equals(platCode)){
				pullOrderLog.setCs_platform_code(PlatConstants.ORDER_SOURCE_AM);//平台号
				orderDealResults= amazonPlatOrderHandler.getOrderByCustomer(customerShop, startTime, endTime, 1); 
			}else if(PlatConstants.ORDER_SOURCE_SMT.equals(platCode)){
				pullOrderLog.setCs_platform_code(PlatConstants.ORDER_SOURCE_SMT);//平台号
				orderDealResults= smtPlatOrderHandler.getOrderByCustomer(customerShop, startTime, endTime, 1); 
			}else{
				throw new CheckDataException("暂时不支持【"+platCode+"】平台!");
			}
		}catch(CheckDataException e){
			LOGGER.error("手动拉单结束---请求参数异常:"+e.getMessage());
			responseMessage.setRsCode(PlatConstants.IS_PULL_SIGN_N);
			responseMessage.setRsDesc(e.getMessage());
			return responseMessage;
		}catch(Exception e){
		   	 Date endTime = new Date(); 
		   	 pullOrderLog.setPull_sign(PlatConstants.IS_PULL_SIGN_N);
		     pullOrderLog.setPull_date_end(dateFormat.format(endTime));//拉单结束时间
		     if(StringUtils.isNotEmpty(pullOrderLog.getFk_cm_id())&&
		    			 StringUtils.isNotEmpty(pullOrderLog.getFk_cs_code())){
		    	 try{ 
				    pullOrderLogDao.savePullOrderLog(pullOrderLog);
				    PullorderLogFail LogFail=new PullorderLogFail();
					LogFail.setError_msg(e.getMessage());
					LogFail.setFk_pol_id(pullOrderLog.getPol_id());
					pullOrderLogDao.savePullLogFail(LogFail);
		    	 }catch(Exception ex){
			    	LOGGER.error("---商家:["+pullOrderLog.getFk_cm_id()+"]-商铺ID:["+pullOrderLog.getFk_cs_code()+"]-"
			    			+ "【保存"+pullOrderLog.getCs_platform_code()+" 平台 手动拉单失败日志时异常】  "+e.getMessage());
			    	
		    	 }
		     }
		     LOGGER.error("手动拉单结束---发生异常:"+e.getMessage());
			 responseMessage.setRsCode(PlatConstants.IS_PULL_SIGN_N);
			 responseMessage.setRsDesc(e.getMessage());
			 return responseMessage;
		}
		int a=0;
		for (OrderDealResult orderDealResult : orderDealResults) {
			if("0".equals(orderDealResult.getRsCode())){
					a++;
			}
		}
		responseMessage.setRsCode(PlatConstants.IS_PULL_SIGN_Y);
		responseMessage.setOrderSuccessNum(a+"");
		responseMessage.setRsDesc("拉单成功");
		LOGGER.info("手动拉单结束---拉单成功");
		return responseMessage;
	}
	
	/**
	 * 
	 * <p>Title: checkRequestParam</p>
	 * <p>Desc: 校检reqpust请求的参数</p>
	 * @author xiangtao(xiangtao@4px.com)
	 * @date 2015年12月23日 下午2:41:05 
	 * @version 1.0
	 * @param map
	 * @throws CheckDataException
	 * @throws ParseException
	 */
	public void checkRequestParam(HttpServletRequest request)throws CheckDataException, ParseException{
		if(request==null){
			throw new CheckDataException("请求参数map 不能为空！");
		}
		if(StringUtils.isEmpty(request.getParameter("cs_id"))){
			throw new CheckDataException("请求参数map属性 cs_id不能为空！");
		}
		if(StringUtils.isEmpty(request.getParameter("platform_code"))){
			throw new CheckDataException("请求参数map属性 platform_code不能为空！");
		}
		if(StringUtils.isEmpty(request.getParameter("start_time"))){
			throw new CheckDataException("请求参数map属性 start_time不能为空！");
		}
		if(StringUtils.isEmpty(request.getParameter("end_time"))){
			throw new CheckDataException("请求参数map属性 end_time不能为空！");
		}
		Calendar  calendarStartTime =
				DateFormatUtils.parseTimestamp(request.getParameter("start_time"), DateFormatUtils.DEFAULTPATTERN);
		Calendar  calendarEndTime = 
				DateFormatUtils.parseTimestamp(request.getParameter("end_time"), DateFormatUtils.DEFAULTPATTERN);
		
		int dateCompareResult = DateFormatUtils.compare(calendarStartTime, calendarEndTime,DateFormatUtils.DEFAULTPATTERN);
		if(dateCompareResult>0){
			throw new CheckDataException("起始时间  不能大于结束时间!");
		}
		SimpleDateFormat format = new SimpleDateFormat(DateFormatUtils.DEFAULTPATTERN);
		String dateTime=format.format(new Date());
		Calendar  calendarDateTime = 
				DateFormatUtils.parseTimestamp(dateTime, DateFormatUtils.DEFAULTPATTERN);
		int timeCompareResult = DateFormatUtils.compare(calendarEndTime, calendarDateTime,DateFormatUtils.DEFAULTPATTERN);
		if(timeCompareResult>0){
			throw new CheckDataException("结束时间  不能大于当前时间!");
		}
		
	}
	
	/**
	 * 
	 * <p>Title: checkRequestParam</p>
	 * <p>Desc: 校检reqpust请求的参数</p>
	 * @author xiangtao(xiangtao@4px.com)
	 * @date 2015年12月23日 下午2:41:05 
	 * @version 1.0
	 * @param map
	 * @throws CheckDataException
	 * @throws ParseException
	 */
	public void checkRequestParam(Map<String,String> reqMap)throws CheckDataException, ParseException{
		if(reqMap==null){
			throw new CheckDataException("请求参数map 不能为空！");
		}
		if(StringUtils.isEmpty(reqMap.get("cs_id"))){
			throw new CheckDataException("请求参数map属性 cs_id不能为空！");
		}
		if(StringUtils.isEmpty(reqMap.get("platform_code"))){
			throw new CheckDataException("请求参数map属性 platform_code不能为空！");
		}
		if(StringUtils.isEmpty(reqMap.get("start_time"))){
			throw new CheckDataException("请求参数map属性 start_time不能为空！");
		}
		if(StringUtils.isEmpty(reqMap.get("end_time"))){
			throw new CheckDataException("请求参数map属性 end_time不能为空！");
		}
		Calendar  calendarStartTime =
				DateFormatUtils.parseTimestamp(reqMap.get("start_time"), DateFormatUtils.DEFAULTPATTERN);
		Calendar  calendarEndTime = 
				DateFormatUtils.parseTimestamp(reqMap.get("end_time"), DateFormatUtils.DEFAULTPATTERN);
		
		int dateCompareResult = DateFormatUtils.compare(calendarStartTime, calendarEndTime,DateFormatUtils.DEFAULTPATTERN);
		if(dateCompareResult>0){
			throw new CheckDataException("起始时间  不能大于结束时间!");
		}
		SimpleDateFormat format = new SimpleDateFormat(DateFormatUtils.DEFAULTPATTERN);
		String dateTime=format.format(new Date());
		Calendar  calendarDateTime = 
				DateFormatUtils.parseTimestamp(dateTime, DateFormatUtils.DEFAULTPATTERN);
		int timeCompareResult = DateFormatUtils.compare(calendarEndTime, calendarDateTime,DateFormatUtils.DEFAULTPATTERN);
		if(timeCompareResult>0){
			throw new CheckDataException("结束时间  不能大于当前时间!");
		}
		
	}
	
	
	/**
	 * 
	 * <p>Title: gotoOrderjsp</p>
	 * <p>Desc: 跳转到操作页面</p>
	 * @author xiangtao(xiangtao@4px.com)
	 * @date 2016年1月21日 下午3:54:34 
	 * @version 1.0
	 * @return
	 */
	@RequestMapping(value="gotoManuallyShopjsp")
	public String gotoOrderjsp(){
		
		return "manually/manually";
	}
	
	@ResponseBody
	@RequestMapping(value="findManuallyShopPage",method=RequestMethod.POST)
	public Map<String,Object> findManuallyShopPage(@RequestParam Map<String,Object> reqMap){
		Map<String,Object> resultMap=new HashMap<String,Object>();
		try
		{	
			resultMap=customerShopService.findManuallyShopPage(reqMap);
			return resultMap;
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return resultMap;
	}
	
	@ResponseBody
	@RequestMapping(value="manuallyPullOrder",method=RequestMethod.POST)
	public Map<String,Object>manuallyPullOrder(@RequestParam Map<String,String>reqMap){
		Map<String,Object> resultMap=new HashMap<String,Object>();
		try{
			checkRequestParam(reqMap);
			List<String> pullOrderList=customerShopService.selectPullCreateDate(reqMap);
			 // 一天拉单最多只能50次
	        if(null != pullOrderList && pullOrderList.size()>=50){
	        	resultMap.put("error", 1);
	        	return resultMap;
	        }
	        if(null != pullOrderList && pullOrderList.size()>0){
	        	String availableTime = pullOrderList.get(0);
                if(availableTime != null && !"".equals(availableTime)){
                	// 为了防止用户频繁的刷统计，暂定5分钟内，不允许用户再操作
        			Date availableDate = DateFormatUtils.getMoveAfterDate(PlatConstants.YYYY_MM_DD_HH_MM_SS,availableTime,PlatConstants.INT_FIVE);
        			
        			Calendar aCalendar = Calendar.getInstance();
        			aCalendar.setTime(availableDate);
        			int dateCompareResult =DateFormatUtils.compare(Calendar.getInstance(),aCalendar,PlatConstants.YYYY_MM_DD_HH_MM_SS);
        			if(dateCompareResult <= 0){
        				resultMap.put("error", 2);
        				return resultMap;
        			}
                }
	        }
	     // 查找获得GU_ID
	        CustomerShop customerShop = customerShopService.findByCsidCustomer(reqMap.get("cs_id"));
			if (customerShop==null) {
				resultMap.put("error", 3);
				return resultMap;
			}
			ResponseMessage rMessage= manuallyGetOrder(reqMap);
			resultMap.put("success", rMessage);
		}catch(Exception e){
			LOGGER.error(e.getMessage());
			resultMap.put("error", 4);	
			return resultMap;
		}
		return resultMap;
	}
	
}

